<template>
  <div class="approve">
    <el-dialog title="登记单" :visible.sync="open" width="70%" append-to-body :before-close="closeDelDialog">
      <div style="width:90%;margin:0 auto;padding:20px 15px; overflow-y: auto; height: 700px">
        <h2>登记单</h2>
        <el-row ref="queryForm">
          <el-col :span="24">
            <el-form ref="registerForm" :model="registerForm" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="8" :xs="24">
                  <el-form-item label="姓名" prop="consultName">
                    <el-input v-model="registerForm.consultName" placeholder="请输入姓名" clearable style="width: 85%; margin-right: 1%;"/>
                    <el-button type="info" icon="el-icon-coordinate" circle @click="readCertCtl"></el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :xs="24">
                  <el-form-item label="单位" prop="nuit">
                    <el-input v-model="registerForm.nuit" placeholder="请输入单位" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :xs="24">
                  <el-form-item label="证件类型" prop="numType">
                    <el-select v-model="registerForm.numType" placeholder="请选择" clearable style="width: 100%">
                      <el-option v-for="dict in dict.type.IDTYPE" :key="dict.value" :label="dict.label"
                                 :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8" :xs="24">
                  <el-form-item label="证件号码" prop="consultNum">
                    <el-input v-model="registerForm.consultNum" placeholder="请输入证件号码" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :xs="24">
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="registerForm.phone" placeholder="请输入联系电话" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :xs="24">
                  <el-form-item label="人次" prop="personNum">
                    <el-select v-model="registerForm.personNum" placeholder="请选择" clearable style="width: 100%">
                      <el-option v-for="dict in numOption" :key="dict.value" :label="dict.label"
                                 :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8" :xs="24">
                  <el-form-item label="政治面貌" prop="politicalOutlook">
                    <el-input v-model="registerForm.politicalOutlook" placeholder="请输入政治面貌" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :xs="24">
                  <el-form-item label="利用目的" porp="utilizeAim">
                    <el-select v-model="registerForm.utilizeAim" placeholder="请选择" clearable style="width: 100%">
                      <el-option v-for="dict in dict.type.DJD_LYMD" :key="dict.value" :label="dict.label"
                                 :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :xs="24">
                  <el-form-item label="查档时间" prop="consultTime">
                    <el-input v-model="registerForm.consultTime" placeholder="请输入查档时间" style="width: 80%; margin-right: 3%" clearable/>小时
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" :xs="24">
                  <el-form-item label="内容用途" prop="useTo">
                    <el-input v-model="registerForm.useTo" placeholder="请输入内容用途" ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" :xs="24">
                  <el-form-item label="备 注" prop="remark">
                    <el-input v-model="registerForm.remark" type="textarea" :rows="3"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" :xs="24">
                  <el-form-item label="介绍信">
                    <el-upload :action="uploadFileUrl" :file-list="fileList" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
                      :show-file-list="true" :headers="headers" class="upload-file-uploader" ref="fileUpload" :on-remove="handleRemove">
                      <div style="width: 100%; display: flex">
                        <el-button type="primary" icon="el-icon-upload" style="padding: 0 10px; height: 40px">上传文件</el-button>
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8" ref="refbut" style="width:90%;margin:0 auto">
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete"  @click="delTap">移除</el-button>
          </el-col>
        </el-row>
        <div class="tableData">
          <el-table :data="tableDataList" @selection-change="handleSelectionChange" border align="center" header-align="center"
                    :loading="loading" :row-key="getRowKeys" lazy :load="load"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column type="selection" width="55" align="center" prop="ID" :selectable="checkboxSelect" />
              <el-table-column prop="TITLE" label="题名" align="center" />
            <el-table-column prop="DH" label="档号" align="center" />
            <el-table-column prop="RQ" label="日期" align="center" />
            <el-table-column prop="BGQX" label="保管期限" align="center">
              <!--<template slot-scope="scope">
                <span v-for="(i, idx) in dict.type.BGQX" :key="idx">
                  {{ scope.row.BGQX == i.value ? i.label : '' }}
                </span>
              </template> -->
            </el-table-column>
          </el-table>
        </div>

        <el-row>
          <el-col :span="24" class="j_content margin_top">
            <el-button type="primary" size="medium  " @click="submitTap">提交</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getLastIndexOf} from "@/utils";
import {getDaList, delArchive, submitRegister, getIpAddress} from "@/api/archive/retrieval/catalogueSearch";
import {getArchiveInfo} from "@/api/archive/archiveBorrow/borrowReceipt.js";
import {getToken} from "@/utils/auth";
import axios from "axios";

export default {
  name: "register",
  props: ['open'],
  archive_Dicts: ['DJD_LYMD', 'BGQX', 'IDTYPE'],
  data() {
    return {
      registerForm: {
        consultName: undefined,
        nuit: undefined,
        numType: undefined,
        consultNum: undefined,
        phone: undefined,
        personNum: undefined,
        politicalOutlook: undefined,
        utilizeAim: undefined,
        consultTime: undefined,
        useTo: undefined,
        remark: undefined,
        introduceLetter: undefined
      },
      rules: {
        consultName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        nuit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        numType: [
          { required: true, message: "证件类型不能为空", trigger: "blur" }
        ],
        consultNum: [
          { required: true, message: "证件号码不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
      },
      numOption: [
        {value: '1', label: '1'},
        {value: '2', label: '2'},
        {value: '3', label: '3'},
        {value: '4', label: '4'},
      ],
      loading: false,
      fileList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/archive/special/subject/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      limit: 1,
      Loading: true,
      tableDataList: [],
      getRowKeys(row) {
        var id=row?.ID==undefined?row.daId: row.ID

        return id;
      },
      timer: null,
      websockets: '',
      isconncet: false,

      idReaderType: ''
    }
  },
  methods: {
    init() {
      this.getConfigKey("IDCARD_READER").then(response => {
        this.idReaderType = response.msg
      });
      this.resetForm("registerForm");
      this.getArchiveList()
    },
    getArchiveList() {
      this.tableDataList = []
      getDaList().then(res=>{
        this.tableDataList = res.rows;
        for (let i = 0; i < res.rows.length; i++) {
          this.tableDataList[i].TITLE = res.rows[i].title
          this.tableDataList[i].DH = res.rows[i].dh
          if (res.rows[i].daMsg && res.rows[i].daMsg !='null') {
            var obj = JSON.parse(res.rows[i].daMsg)
            this.tableDataList[i].BGQX = obj.BGQX;
            for (let j = 0; j < this.dict.type.BGQX.length; j++) {
              if (obj.BGQX == this.dict.type.BGQX[j].value) {
                this.tableDataList[i].BGQX = this.dict.type.BGQX[j].label
                break;
              }
            }
            this.tableDataList[i].RQ = obj.RQ
            this.tableDataList[i].SUB_TABLE_NAME = obj.SUB_TABLE_NAME
            this.tableDataList[i].ID = obj.DA_ID
            this.tableDataList[i].CATEGORY_ID = obj.categoryId
            this.tableDataList[i].hasChildren = true
          }
        }


        console.log(this.tableDataList)
      })
    },
    closeDelDialog() {
      this.fileList = []
      this.$emit("closeDelDialog")
    },
    // 文件上传 - 文件选中后上传
    handleChange(file, fileList) {
      /* 自动上传改成true会导致重复触发，所以在handleChange上传文件*/
      //  防抖
      let length = fileList.length
      this.fileList = fileList
      this.maxLength = Math.max(length, this.maxLength)
      setTimeout(() => {
        if (length === this.maxLength) {
          // 你的上传文件逻辑
          this.$refs.uploadComp.submit();
        }
      }, 100)
    },
    handleRemove() {
      this.fileList = []
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.registerForm.introduceLetter = res.data.url
      }
    },
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    delTap() {
      if (this.multiple) {
        this.$message({ message: '请选择要移除的数据哦', type: 'warning' })
      } else {
        this.$modal.confirm('是否确认所选数据项？').then(() => {
          delArchive(this.ids.toString()).then(res => {
            this.$modal.msgSuccess("删除成功");
            this.getArchiveList();
          })
        }).catch(() => { });

      }
    },
    // 懒加载表格数据
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        var level = "";
        if (tree.SUB_TABLE_NAME != undefined) {
          if (getLastIndexOf(tree.SUB_TABLE_NAME) == "F") {  //F 件
            level = 'efile'
          } else if (getLastIndexOf(tree.SUB_TABLE_NAME) == "V") { //卷
            level = 'jian'
          } else { //项目
            level = 'juan'
          }
          const menuId = this.$route.meta.menuId
          const archiveId = tree.daId ==undefined ?tree.ID: tree.daId
          const categoryId = tree.CATEGORY_ID
          if(level != 'efile') {
            getArchiveInfo(
              {
                menuId: menuId, level: level, archiveId: archiveId, categoryId: categoryId
              }
            ).then(response=> {
              for (let i = 0; i < response.rows.length; i++) {
                response.rows[i].hasChildren = true
                response.rows[i].isChildren = '1'
                for (let j = 0; j < this.dict.type.BGQX.length; j++) {
                  if (response.rows[i].BGQX == this.dict.type.BGQX[j].value) {
                    response.rows[i].BGQX = this.dict.type.BGQX[j].label
                    break;
                  }
                }
              }
              resolve(response.rows)
            })
          } else {
            resolve([])
          }
        } else {
          resolve([])
        }
      }, 1000)
    },
    // 是否禁用多选框
    checkboxSelect(row) {
      if(row.isChildren == '1') {
        return false
      } else {
        return true
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    submitTap() {
      this.$refs["registerForm"].validate(valid => {
        if (valid) {
          this.registerForm.cuIds = this.tableDataList.map(item => item.id).toString()
          this.$modal.confirm('是否确认提交？').then(() => {
            submitRegister(this.registerForm).then(res=>{
              this.$modal.msgSuccess('提交成功')
              this.closeDelDialog()
            })
          }).catch(()=>{})
        }
      })
    },
    readCertCtl(){
      if (this.idReaderType == 'Windows') {
        // windows
        this.OcrRecognition();
      } else if (this.idReaderType == 'HuaShi') {
        // 华视
        this.timer = setInterval(() => {
          this.readCert();
        }, 2000);
      }
    },
    // ajax(options) {
    //   if(options.type==null)
    //   {
    //     options.type="POST";
    //   }
    //
    //   if(options.url==null)
    //   {
    //     options.url="";
    //   }
    //
    //   if(options.timeout==null)
    //   {
    //     options.timeout=5000;
    //   }
    //
    //   if(options.onComplate==null)
    //   {
    //     options.onComplate=function()
    //     {
    //     }
    //   }
    //
    //   if(options.onError==null)
    //   {
    //     options.onError=function()
    //     {
    //     }
    //   }
    //
    //   if(options.onSuccess==null)
    //   {
    //     options.onSuccess=function()
    //     {
    //     }
    //   }
    //
    //   if(options.data)
    //   {
    //     options.data="";
    //   }
    //
    //   var xml ;
    //   if (typeof ActiveXObject != 'undefined') {
    //     var aVersions = ["Microsoft.XMLHTTP", "Msxml2.XMLHttp.6.0", "Msxml2.XMLHttp.5.0", "Msxml2.XMLHttp.4.0", "Msxml2.XMLHttp.3.0"];
    //     for (var i = 0; i < aVersions.length; i++) {
    //       try {
    //         xml = new ActiveXObject(aVersions[i]);
    //       }catch (e) {}
    //     }
    //   } else if (typeof XMLHttpRequest != 'undefined'){
    //     xml = new XMLHttpRequest();
    //   }
    //
    //   xml.open(options.type, options.url, true);
    //
    //   var timeoutLength = options.timeout;
    //
    //   var requestDone = false;
    //
    //   setTimeout(function() {
    //     requestDone = true;
    //   }, timeoutLength);
    //
    //   xml.onreadystatechange = function() {
    //
    //     if (xml.readyState == 4 && !requestDone) {
    //
    //       if (httpSuccess(xml)) {
    //
    //         options.onSuccess(httpData(xml));
    //       }
    //
    //       else {
    //         options.onError();
    //       }
    //
    //       options.onComplate();
    //
    //       xml = null;
    //     }
    //   };
    //
    //   xml.send();
    //
    //   function httpSuccess(r) {
    //     try {
    //       return !r.status && location.protocol == "file:"
    //         ||
    //         (r.status >= 200 && r.status <= 300)
    //         ||
    //         r.status == 304
    //         ||
    //
    //         navigator.userAgent.indexOf("Safari") >= 0
    //         && typeof r.status == "undefined";
    //     } catch (e) {
    //     }
    //     return false;
    //   }
    //
    //   function httpData(r) {
    //     var ct = r.getResponseHeader("responseType");
    //     if(ct)
    //     {
    //       if(ct=="script")
    //       {
    //         eval.call(window, data);
    //       }
    //       if(ct=="xml")
    //       {
    //         return r.responseXML;
    //       }
    //       if(ct=="json")
    //       {
    //         return JSON.parse(r.responseText);
    //       }
    //     }
    //     return r.responseText;
    //   }
    // },
    // clearForm() {
    //   document.getElementById("certType").value = "";
    //   document.getElementById("timeElapsed").value = "";
    //   document.getElementById("partyName").value = "";
    //   document.getElementById("gender").value = "";
    //   document.getElementById("nation").value = "";
    //   document.getElementById("bornDay").value = "";
    //   document.getElementById("certAddress").value = "";
    //   document.getElementById("certNumber").value = "";
    //   document.getElementById("certOrg").value = "";
    //   document.getElementById("effDate").value = "";
    //   document.getElementById("expDate").value = "";
    //   document.getElementById("result").value = "";
    // },
    readCert() {
      getIpAddress().then(res=>{
        const backendIP = res.msg
        // options.url="http://192.168.2.159:8000/cgi-bin/readCard";
        //options.url="cgi-bin/readCard";
        axios({
          method: 'POST',
          url: `http://${backendIP}:8000/cgi-bin/readCard`,
          timeout: 5000,
        }).then(response => {
          // 处理成功的回调函数
          // console.log(response, '=====================')
          if (response.data.result.resultFlag == 0) {
            clearInterval(this.timer);
            // console.log(response.data.info)
            let obj = response.data.info
            var certType = obj.certType
            if(certType == 0) {
              // certType = "身份证";
              certType = "1";
            } else if(certType == 1) {
              // certType = "外国人居住证";
              certType = "3";
            } else if(certType == 2) {
              // certType = "港澳台居住证";
              certType = "9";
            } else {
              // certType = "未知";
              certType = "10";
            }
            this.registerForm.numType = certType
            this.registerForm.consultNum = obj.idCode
            this.registerForm.consultName = obj.name
          } else {
            this.$modal.msgWarning('未读取到信息')
          }
        }).catch(error => {
          // 处理失败的回调函数
          console.error('Error:', error);
        });
      })
    },

    /**
     *   建立连接
     */
    OcrRecognition() {
      if (!this.isconncet) {
        // 1. 创建websockets对象，参数为服务器websockets地址
        let hostname = location.hostname;
        getIpAddress().then(res=>{
          const backendIP = res.msg
          console.log(backendIP)
          var url = "ws:" + backendIP + ":7415";
          // var url = "ws:192.168.2.118:7415";
          this.websockets = new WebSocket(url);

          // 2.监听websocket的状态变化，接收的信息，关闭时的状态

          //监听连接状态的变化
          this.websockets.onopen = (event) => this.socketChange();

          //监听接收消息的情况
          this.websockets.onmessage = (res) => {
            if (res.data == "failed to obtain ID card information") {
              //document.querySelector("#message").innerHTML += `<p>接收数据: ${res.data}</p>`
              return;
            }
            var alldata = res.data.split("|");
            if (alldata.length >= 17) {
              if (alldata[0] == '身份证') {
                this.registerForm.numType = '1'
                this.registerForm.consultName = alldata[1];
                this.registerForm.consultNum = alldata[6];
              }
              //document.getElementById("partyLog").value = "读卡成功";
              // document.getElementById("userName").value = alldata[1];
              /* document.getElementById("nation").value = alldata[3];
              document.getElementById("gender").value = alldata[2];
              document.getElementById("certAddress").value = alldata[5];
              document.getElementById("bornDay").value = alldata[4]; */
              // document.getElementById("idCard").value = alldata[6];
              /* document.getElementById("certOrg").value = alldata[7];
              document.getElementById("effDate").value = alldata[8];
              document.getElementById("expDate").value = alldata[9];
              document.all['PhotoDisplay'].src = 'data:image/bmp;base64,' + alldata[17]; */
            } else {
              //document.getElementById("partyLog").value = res.data;
            }

          }

          //监听关闭时的状态变化
          this.websockets.onclose = (event) => this.socketChange();
        })
      } else {
        //closeConnect();
        //document.getElementById("OcrRecognition").innerHTML = "连接服务";
      }
    },

    ReadIDCardNoJudge() {
      if (!this.isconncet) {
        //document.getElementById("partyLog").value = "未连接服务";
      } else {
        //clear();
        let paramTimeOut = 10000;
        paramTimeOut = "timeout=" + paramTimeOut;
        var parameterAll = paramTimeOut;
        let val = "04?" + parameterAll;
        this.websockets.send(val);
      }
    },
    /**
     *   socket状态变化
     */
    socketChange() {
      let state = this.websockets.readyState;
      // let val = statusArr.map((item) => {
      //   if (item.state == state) {
      //     return item.value
      //   }
      // });
      //实时显示状态的变化
      //document.getElementById("partyLog").value = val;
      //读身份证
      if (1 == state) {
        this.isconncet = true;
        this.ReadIDCardNoJudge();
        setTimeout(() => {
          this.closeConnect();
        }, 5000);
        //document.getElementById("OcrRecognition").innerHTML = "断开服务";
      }
      if (3 == state) {
        this.isconncet = false;
      }
    },
    /**
     *   关闭连接
     *
     */
    closeConnect() {
      this.websockets.close();
    },
  }
}
</script>

<style lang="scss" scoped>
h2 {
  display: block;
  text-align: center;
  line-height: 30px;
  font-size: 30px;
  font-weight: bold;
}

.j_content {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.margin_top {
  margin-top: 20px
}

.tableData {
  width: 95%;
  margin-left: 5%;
}
</style>
